
<!-- 样式 -->
<script type="text/html" template>
  <link rel="stylesheet" href="{{ layui.setter.base }}style/css/reset.css">
  <link rel="stylesheet" href="{{ layui.setter.base }}style/css/maintain/details.css">
  <link rel="stylesheet" href="{{ layui.setter.base }}style/css/maintain/new_plan.css">
  <link rel="stylesheet" href="{{ layui.setter.base }}style/autoComplete.css">
  <link rel="stylesheet" href="{{ layui.setter.base }}style/css/patrol/project_device_alert.css">
</script>
<style scoped>
  .footer button{
    border: 0;
  }
</style>
<div class="layui-containner leon-style" id="onlyReadContent">
<div class="layui-fluid">
  <div class="layui-title">
    巡检计划详细信息
    <i class="layui-icon layui-icon-edit showCanEdit" style="cursor: pointer; font-size: 15px;color: #616161;"></i>
  </div>
  <ul class="box layui-row baseInfo">
  </ul>
</div>
<div class="layui-fluid tableInfo">
  <div class="layui-title">
    <span class="layui-title-inner">巡检设备基本信息</span>
  </div>
  <table class="layui-table" lay-size="sm" id="readOnlyBaseTable">
    <thead>
      <tr>
        <th rowspan="2">设备编号</th>
        <th rowspan="2">设备名称</th>
        <th rowspan="2">设备类型</th>
        <th rowspan="2">供应商</th>
        <th rowspan="2">设备系列</th>
        <th rowspan="2">设备型号</th>
        <th colspan="6">巡检项目</th>
      </tr>
      <tr>
        <th width="10%">项目名称</th>
        <th width="10%">项目说明</th>
        <th width="10%">单位</th>
        <th width="10%">最高标准值</th>
        <th width="10%">最低标准值</th>
      </tr>
    </thead>
    <tbody>
    </tbody>
  </table>
  <footer class="footer layui-btn-containner">
    <button class="onOff-btn footer-btn layui-btn layui-btn-radius layui-btn-primary">启用/停用</button>
    <button class="cancel-btn footer-btn layui-btn layui-btn-radius layui-btn-primary">取消</button>
  </footer>
</div>
</div>

<div class="layui-containner leon-style hide" id="canEditContent">
<form class="layui-form" action="" lay-filter="tcPlanForm">
  <div class="layui-fluid">
    <div class="layui-title">巡检计划详细信息<span class="cancelBtn"
        style="cursor: pointer; font-size: 13px; margin-left: 10px; color: #616161;">取消编辑</span></div>
    <ul class="box layui-row baseInfo">
      <li class="layui-col-md3 layui-col-sm3">
        <input type="text" name="tcPlanId" readonly style="display:none" />
        <div class="layui-input-block">
          <span class="inner">
            巡检计划编号:
          </span>
          <span class="layui-input-box">
            <input type="text" lay-verify="required" required name="tcPlanCode" class="layui-input" style="border: 0;" disabled>
          </span>
        </div>
        <div class="layui-input-block">
          <span class="inner">
            <span style="font-size: 18px;color: red;position: relative;display: inline-block;line-height: 20px;vertical-align: middle;top:3px;">*</span>
            巡检计划名称:
          </span>
          <span class="layui-input-box">
            <input type="text" lay-verify="required" required name="tcPlanName" class="layui-input">
          </span>
        </div>
        <div class="layui-input-block">
          <span class="inner">
            巡检计划状态:
          </span>
          <span class="layui-input-box">
            <div class="layui-input-block"  lay-filter="tcPlanStatus" id="tcPlanStatus">
              <input type="radio" name="tcPlanStatus" value="0" title="启用" checked>
              <input type="radio" name="tcPlanStatus" value="1" title="停用">
            </div>
          </span>
        </div>
        <div class="layui-input-block">
          <span class="inner">
            <span style="font-size: 18px;color: red;position: relative;display: inline-block;line-height: 20px;vertical-align: middle;top:3px;">*</span>
            计划开始时间:
          </span>
          <span class="layui-input-box">
            <input type="text" name="tcPlanStart" required lay-verify="required" id="startTime" placeholder=""
              autocomplete="off" class="layui-input ">
          </span>
        </div>
      </li>
      <li class="layui-col-md3 layui-col-sm3">
        <div class="layui-input-block">
          <span class="inner">
            计划结束时间:
          </span>
          <span class="layui-input-box">
            <input type="text" name="tcPlanEnd" id="endTime" placeholder="" autocomplete="off" class="layui-input ">
          </span>
        </div>
        <div class="layui-input-block">
          <span class="inner">
            <span style="font-size: 18px;color: red;position: relative;display: inline-block;line-height: 20px;vertical-align: middle;top:3px;">*</span>
            巡检计划频率:
          </span>
          <span class="layui-input-box">
            <select name="tcPlanFrequency" lay-filter="tcPlanFrequency" lay-verify="required" required id="frequency">
              <option value=""></option>
              <option value="H">每小时</option>
              <option value="D">每日</option>
              <option value="W">每周</option>
              <option value="M">每月</option>
            </select>
          </span>
        </div>
        <div class="layui-input-block">
          <span class="inner">
            计划频率日期:
          </span>
          <span class="layui-input-box freq">
            <input type="text" name="tcPlanDay" id="tcPlanDay" lay-verify="checkPlanDay" id="tcPlanDate"
              placeholder="" autocomplete="off" class="layui-input">
          </span>
        </div>
        <div class="layui-input-block">
          <span class="inner">
            <span style="font-size: 18px;color: red;position: relative;display: inline-block;line-height: 20px;vertical-align: middle;top:3px;">*</span>
            巡检时间:
          </span>
          <span class="layui-input-box">
            <input type="text" name="tcPlanTime" id="tcPlanTime" required lay-verify="required" id="tcPlanTime"
              placeholder="" autocomplete="off" class="layui-input ">
          </span>
        </div>
      </li>
      <li class="layui-col-md3 layui-col-sm3">
        <div class="layui-input-block">
          <span class="inner">
            <span style="font-size: 18px;color: red;position: relative;display: inline-block;line-height: 20px;vertical-align: middle;top:3px;">*</span>
            执行时长:
          </span>
          <span class="layui-input-box layui-form">
            <div class="layui-form" lay-filter="testFame" style="display: flex;" lay-verify="toPlanDuration">
              <select name="hour" id="hour">
                  <option value="00">00小时</option>
                  <option value="01">01小时</option>
                  <option value="02">02小时</option>
                  <option value="03">03小时</option>
                  <option value="04">04小时</option>
                  <option value="05">05小时</option>
                  <option value="06">06小时</option>
                  <option value="07">07小时</option>
                  <option value="08">08小时</option>
                  <option value="09">09小时</option>
                  <option value="10">10小时</option>
                  <option value="11">11小时</option>
                  <option value="12">12小时</option>
              </select>
              <select name="minute" id="minute">
                  <option value="00">00分</option>
                  <option value="30">30分</option>
              </select>
            </div>
          </span>
          
        </div>
        <div class="layui-input-block">
          <span class="inner">
            <span style="font-size: 18px;color: red;position: relative;display: inline-block;line-height: 20px;vertical-align: middle;top:3px;">*</span>
            巡检负责人:
          </span>
          <div class="layui-input-box completeWrap" style="position: relative">
            <input name="tcPlanGen01" id="gen02" value="" autocomplete="off" class="layui-input" required
              lay-verify="required" />
          </div>
        </div>
        <div class="layui-input-block">
          <span class="inner">
            上次巡检时间:
          </span>
          <span class="layui-input-box">
          </span>
        </div>
        <div class="layui-input-block">
          <span class="inner">
            下次巡检时间:
          </span>
          <span class="layui-input-box">
          </span>
        </div>
      </li>
      <li class="layui-col-md3 layui-col-sm3">
        <div class="layui-radio-box layui-input-block">
          <label>是否自动生成工单:</label>
          <div class="layui-input-box" style="text-align: center;">
            <input type="radio" name="tcPlanIsAuto" value="1" title="是" class="layui-radio" checked="">
            <input type="radio" name="tcPlanIsAuto" value="0" title="否" class="layui-radio">
          </div>
        </div>
        <div class="layui-input-block layui-textarea-block">
          <span class="inner">
            巡检说明:
          </span>
          <span class="layui-input-box">
            <textarea class="layui-textarea" name="tcPlanDsc" lay-verify=""></textarea>
          </span>
        </div>
        <div class="layui-input-block layui-textarea-block">
          <span class="inner">
            <span style="font-size: 18px;color: red;position: relative;display: inline-block;line-height: 20px;vertical-align: middle;top:3px;">*</span>
            位置范围:
          </span>
          <span class="layui-input-box">
            <textarea class="layui-textarea" name="tcPlanArea" required lay-verify="required"></textarea>
          </span>
        </div>
      </li>
    </ul>
  </div>
  <div class="layui-fluid tableInfo">
    <div class="layui-title">
      <span class="layui-title-inner">巡检设备基本信息填写</span>
    </div>
    <div class="btn-box layui-btn-containner">
      <button type="button" class="btn-one layui-btn layui-btn-radius layui-btn-primary">
        <i class="layui-icon layui-icon-add-circle" style="font-size: 15px; color: #FFF;"></i>
        <span>添加巡检设备</span>
      </button>
      <button type="button" class="btn-two layui-btn layui-btn-radius layui-btn-primary">
        <i class="layui-icon layui-icon-add-circle" style="font-size: 15px; color: #FFF;"></i>
        <span>添加巡检项目</span>
      </button>
      <button type="button" class="btn-three layui-btn layui-btn-radius layui-btn-primary" id="deleteBaseInfo" style="display: flex;vertical-align: middle;line-height: 20px;">
        <i class="layui-icon layui-icon-delete" style="font-size: 15px; color: #FFF;line-height: 20px;position: relative;
        top: -1px;"></i>
        <span>删除巡检设备</span>
      </button>
    </div>

    <table class="layui-table" lay-size="sm" id="baseTable">
      <thead>
        <tr>
          <th rowspan="2"></th>
          <th rowspan="2">设备编号</th>
          <th rowspan="2">设备名称</th>
          <th rowspan="2">设备类型</th>
          <th rowspan="2">供应商</th>
          <th rowspan="2">设备系列</th>
          <th rowspan="2">设备型号</th>
          <th colspan="6">巡检项目</th>
        </tr>
        <tr>
          <th width="8%">项目名称</th>
          <th width="8%">项目说明</th>
          <th width="8%">单位</th>
          <th width="8%">最高标准值</th>
          <th width="8%">最低标准值</th>
          <th width="8%">操作</tr>
      </thead>
      <tbody>
      </tbody>
    </table>
    <footer class="footer layui-btn-containner">
      <button type="button" class="footer-btn confirm-btn layui-btn layui-btn-radius layui-btn-primary layui-bg-red" lay-submit
        lay-filter="save">提交</button>
      <button type="button" class="footer-btn cancel-btn layui-btn layui-btn-radius layui-btn-primary">取消</button>
    </footer>
  </div>
</form>
</div>
<script type="text/html" id="addDeviceTpl">
  <style scoped>
    .leon-style-alert .layui-input-block,.leon-style-alert .con2 input{
    width:50%
  }
  .leon-style-alert .con2{
    padding: 0 20px;
  }
  .leon-style-alert .con2 input{
    width: 100%;
  }
  .leon-style-alert .query{
    display: block;
  }
  .leon-style-alert .layui-form-item{
    clear: none;
    width: 30%;
  }
</style>
<div class="leon-style-alert">
  <div class="layui-alert-box">
      <div class="layui-alert-title">
          <span class="layui-title-inner">巡检设备选择</span>
          <span class="layui-title-screen">
              <div class="screen-btn">
                  <form class="layui-form" action="">
                  <input type="search" name="keyWord" class="search-blank-inner searchInput" placeholder="搜索" autocomplete="off"/>
                  <button type="button" lay-submit lay-filter="queryTableDeviceHeader" class="search-blank-icon"></button>
                  </form>
              </div>
          </span>
      </div>
      <div class="layui-content">
          <div class="con1 toggle-btn">
              <span class="screen">
                  <i class="query-icon  layui-icon"></i>
                  <span class="query-inner">查询条件</span>
              </span>
              <i class="icon layui-icon layui-icon-down"></i>
          </div>
          <div class="con2 toggle-content">
              <form  class="layui-form">
                <div class="layui-form-item layui-col-sm3 layui-col-md3">
                  <label class="layui-form-label">设备编号：</label>
                  <div class="layui-input-block">
                    <input type="text" name="fia01" autocomplete="off" class="layui-input " />
                  </div>
                </div>
                <div class="layui-form-item layui-col-sm3 layui-col-md3">
                  <label class="layui-form-label">设备名称：</label>
                  <div class="layui-input-block">
                    <input type="text" name="fia02" autocomplete="off" class="layui-input " />
                  </div>
                </div>
                <div class="layui-form-item layui-col-sm3 layui-col-md3">
                  <label class="layui-form-label">供应商：</label>
                  <div class="layui-input-block">
                    <input type="text" name="fia09" autocomplete="off" class="layui-input " />
                  </div>
                </div>
                <div class="layui-form-item layui-col-sm6 layui-col-md6">
                  <label class="layui-form-label">是否启用：</label>
                  <div class="layui-input-block">
                    <select name="tcDevIsDisable" autocomplete="off">
                      <option value=""></option>
                      <option value="0">启用</option>
                      <option value="1">停用</option>
                    </select> 
                  </div>
                </div>
                <div class="layui-form-item layui-col-sm6 layui-col-md6">
                  <label class="layui-form-label">设备状态：</label>
                  <div class="layui-input-block">
                    <select name="fiaacti" autocomplete="off">
                      <option value=""></option>
                      <option value="0">一般</option>
                      <option value="1">良好</option>
                      <option value="2">不稳定</option>
                      <option value="3">折旧中</option>
                      <option value="4">外送</option>
                      <option value="5">折毕</option>
                      <option value="6">出售</option>
                      <option value="7">报废</option>
                      <option value="8">折毕再提</option>
                      <option value="9">改良</option>
                      <option value="A">重估</option>
                    </select> 
                  </div>
                </div>
                <button type="button" lay-submit lay-filter="queryTableDevice"
                  class="query layui-btn layui-btn-radius layui-btn-primary">
                  <span class="search-icon"></span>
                  <span class="btn-inner">查询</span>
                </button>
              </form>
          </div>
          <table class="layui-table" id="table-device-alert"></table>
      </div>
      <div class="footer layui-btn-containner">
          <button class="btn1 layui-btn layui-btn-radius layui-btn-primary">添加</button>
          <button class="btn2 layui-btn layui-btn-radius layui-btn-primary">取消</button>
      </div>
  </div>
</div>
</script>
<!-- 巡检项目选择 -->
<script type="text/html" id="addProjectTpl">
<div class="leon-style-alert">
  <div class="layui-alert-box">
      <div class="layui-alert-title">
          <span class="layui-title-inner">巡检项目选择</span>
          <span class="layui-title-screen">
              <div class="screen-btn">
                  <form action="" class="layui-form">
                  <input type="search" name="keyWord" class="search-blank-inner searchInput" placeholder="搜索" autocomplete="off"/>
                  <button type="button" lay-submit lay-filter="queryTableProjectHeader" class="search-blank-icon"></button>
                  </form>
              </div>
          </span>
      </div>
      <div class="layui-content">
          <div class="con1 toggle-btn">
              <span class="screen">
                  <i class="query-icon  layui-icon"></i>
                  <span class="query-inner">查询条件</span>
              </span>
              <i class="icon layui-icon layui-icon-down"></i>
          </div>
          <div class="con2 toggle-content">
              <form action="" class="layui-form">
                  <label for="">项目名称:</label>
                  <input type="text" name="tcInspName" />
                  <label for="">单位:</label>
                  <input type="text" name="tcInspUnit" />
                  <button type="button" lay-submit lay-filter="queryTableProject" class="query layui-btn layui-btn-radius layui-btn-primary">
                      <span class="search-icon"></span>
                      <span class="btn-inner">查询</span>
                  </button>
              </form>
          </div>
          <table class="layui-table" id="table-project-alert"></table>
      </div>
      <div class="footer layui-btn-containner">
          <button class="btn1 layui-btn layui-btn-radius layui-btn-primary">添加</button>
          <button class="btn2 layui-btn layui-btn-radius layui-btn-primary">取消</button>
      </div>
  </div>
</div>
</script>

<script type="text/template" id="baseInfoTPL">
<li class="layui-col-md3 layui-col-sm3">
    <div class="layui-input-block">
      <span class="inner">
        <span style="font-size: 18px;color: red;position: relative;display: inline-block;line-height: 20px;vertical-align: middle;top:3px;">*</span>
        巡检计划名称:</span>
      <span class="layui-input-box">
        {{ d.planid.tcPlanName || ''}}
      </span>
    </div>
    <div class="layui-input-block">
      <span class="inner">巡检计划编号:</span>
      <span class="layui-input-box">
        {{ d.planid.tcPlanCode || '' }}
      </span>
    </div>
    <div class="layui-input-block">
      <span class="inner">巡检计划状态:</span>
      <span class="layui-input-box">
        {{  +d.planid.tcPlanStatus == 0 ? '启用' : '停用' }}
      </span>
    </div>
    <div class="layui-input-block">
      <span class="inner">
        <span style="font-size: 18px;color: red;position: relative;display: inline-block;line-height: 20px;vertical-align: middle;top:3px;">*</span>
        计划开始时间:
      </span>
      <span class="layui-input-box">
        {{  d.planid.tcPlanStart || '' }}
      </span>
    </div>
</li>
<li class="layui-col-md3 layui-col-sm3">
    <div class="layui-input-block">
      <span class="inner">计划结束时间:</span>
      <span class="layui-input-box">
        {{ d.planid.tcPlanEnd || '' }}
      </span>
    </div>
    <div class="layui-input-block">
      <span class="inner">
        <span style="font-size: 18px;color: red;position: relative;display: inline-block;line-height: 20px;vertical-align: middle;top:3px;">*</span>
        巡检计划频率:
      </span>
      <span class="layui-input-box">
        {{ d.planid.tcPlanFrequency || ''}}
      </span>
    </div>
    <div class="layui-input-block">
      <span class="inner">计划频率日期:</span>
      <span class="layui-input-box">
        {{ d.planid.tcPlanDay || '' }}
      </span>
    </div>
    <div class="layui-input-block">
      <span class="inner">*巡检时间:</span>
      <span class="layui-input-box">
        {{ d.planid.tcPlanTime || '' }}
      </span>
    </div>
</li>
<li class="layui-col-md3 layui-col-sm3">
    <div class="layui-input-block">
      <span class="inner">
        <span style="font-size: 18px;color: red;position: relative;display: inline-block;line-height: 20px;vertical-align: middle;top:3px;">*</span>
        执行时长:
      </span>
      <span class="layui-input-box">
        {{ d.planid.tcPlanDuration }}
      </span>
    </div>
    <div class="layui-input-block">
      <span class="inner">
        <span style="font-size: 18px;color: red;position: relative;display: inline-block;line-height: 20px;vertical-align: middle;top:3px;">*</span>
        巡检负责人:
      </span>
      <span class="layui-input-box">
        {{ d.planid.gen02 || '' }}
      </span>
    </div>
    <div class="layui-input-block">
      <span class="inner">上次巡检时间:</span>
      <span class="layui-input-box">
        {{ d.planid.lastPlanTime || '' }}
      </span>
    </div>
    <div class="layui-input-block">
      <span class="inner">下次巡检时间:</span>
      <span class="layui-input-box">
        {{ d.planid.nextPlanTime || '' }}
      </span>
    </div>
</li>
<li class="layui-col-md3 layui-col-sm3">
    <div class="layui-input-block">
      <span class="inner">是否自动生成工单:</span>
      <span class="layui-input-box">
        {{ +d.planid.tcPlanIsAuto == 1 ? '是' : '否' }}
      </span>
    </div>
    <div class="layui-input-block">
      <span class="inner">巡检说明:</span>
      <span class="layui-input-box">
        {{ d.planid.tcPlanDsc || '' }}
      </span>
    </div>
    <div class="layui-input-block">
      <span class="inner">
        <span style="font-size: 18px;color: red;position: relative;display: inline-block;line-height: 20px;vertical-align: middle;top:3px;">*</span>
        位置范围:
      </span>
      <span class="layui-input-box">
        {{ d.planid.tcPlanArea || '' }}
      </span>
    </div>
</li>
</script>

<script>
! function () {
  //无需再执行layui.use()方法加载模块，直接使用即可
  var $ = layui.$;
  layui.use(['form', 'table', 'api', 'utill', 'view', 'laydate','admin'], function () { //此段代码必不可少
    var table = layui.table,
      setter = layui.setter,
      laytpl = layui.laytpl,
      laydate = layui.laydate,
      api = layui.api,
      utill = layui.utill,
      form = layui.form,
      element = layui.element,
      laypage = layui.laypage,
      view = layui.view,
      admin = layui.admin,
      form = layui.form;
      form.render();
      var status = {
        deviceIndexArr: [],
        planDetails: [],
        tcPlanFrequency: ''
      }
    // 初始化
    var init = function () {
      utill.loading.show();
      view.req({
        url: api.host + api.xjjh.selectPlan,
        type: 'POST',
        data: {
          planId: utill.getQueryVariable('planId')
        },
      }).done(function (res) {
        utill.loading.hide();
        if (+res.code == 0) {
          var planid = res.data.planid;
          var planidCopy = utill.deepCopy(planid)
          var planDetail = res.data.planDetails;
          switch (planidCopy.tcPlanFrequency) {
            case 'W':
              var tcPlanDayArr = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'];

              planidCopy['tcPlanDay'] = tcPlanDayArr[+planidCopy.tcPlanDay - 1]
              break;
            case 'M':
              planidCopy['tcPlanDay'] = planidCopy.tcPlanDay + '号'
              break;
            default:
              planidCopy['tcPlanDay'] = ''
              break;   
          }
          if (planidCopy.tcPlanFrequency == 'H') {
            planidCopy['tcPlanFrequency'] = '每小时'
          } else if (planidCopy.tcPlanFrequency == 'D') {
            planidCopy['tcPlanFrequency'] = '每日'
          } else if (planidCopy.tcPlanFrequency == 'W') {
            planidCopy['tcPlanFrequency'] = '每周'
          } else if (planidCopy.tcPlanFrequency == 'M') {
            planidCopy['tcPlanFrequency'] = '每月'
          } else {
            planidCopy['tcPlanFrequency'] = ''
          }

          var tcPlanDuration = planidCopy.tcPlanDuration + '';
          

          if(tcPlanDuration.split(',')[0] >= 10){
             var hour = tcPlanDuration.split(',')[0];
          }else{
             var hour = "0"+tcPlanDuration.split(',')[0];
          }
          if(tcPlanDuration.split(',')[1] == 3){
            var minute = tcPlanDuration.split(',')[1]+"0";
          }else{
            var minute = tcPlanDuration.split(',')[1];
          }
          $("#hour").val(hour);
          $("#minute").val(minute);
          if (tcPlanDuration.indexOf(',') != -1) {
            planidCopy['tcPlanDuration'] = tcPlanDuration.split(',')[0] + '小时' + tcPlanDuration.split(',')[1]+ '分'
          } else {
            planidCopy['tcPlanDuration'] = tcPlanDuration 
          }
          $('.onOff-btn').html(planid.tcPlanStatus == 0 ? '停用' : '启用');
          $('#onlyReadContent').find('.baseInfo').html(laytpl($('#baseInfoTPL').html()).render({ planid: planidCopy }));

          // 组装编辑数据
          form.val('tcPlanForm', planid);
          if(planid.tcPlanStatus1 == 1){
            let html = `<button type="button" class="footer-btn submit-btn layui-btn layui-btn-radius layui-btn-primary layui-bg-blue">保存</button>`;
            $('#canEditContent .confirm-btn').after(html);
            $('footer').on('click','.submit-btn',function(){
              let data = form.val("tcPlanForm");
              data.tcPlanStatus1 = planid.tcPlanStatus1;
              var opts = {
                planDetails: status.planDetails
              }
              opts = $.extend({}, opts, data);
              opts['tcPlanGen01'] = $('#gen02').data('id');
              utill.loading.show();
              if(data.tcPlanName == ''){
                layer.open({
                  content: '请填写巡检计划名称!'
                })
              }else{
                admin.req({
                  url: api.host + api.xjjh.addDetailAndProjdect,
                  type: "POST",
                  data: JSON.stringify(opts),
                  contentType: "application/json",
                  success: function(res){
                    if(res.code == 0){
                      layer.open({
                        content: res.message
                      });
                      setTimeout(function(){
                        location.hash = '/patrol/balance'
                      },1500);
                    }else{
                      layer.open({
                        content: res.message
                      });
                    }
                  }
                })
              }
            })
          }
          planid.gen02 && $('[name="tcPlanGen01"]').val(planid.gen02)
          // 哈哈
          // planid.tcPlanDuration && $('[name="tcPlanDuration"]').val(planid.tcPlanDuration.toFixed(1))

          status.tcPlanFrequency = planid.tcPlanFrequency;
          if (planid.tcPlanFrequency == 'W' || planid.tcPlanFrequency == 'M') {
            $('[name="tcPlanDay"]').val(planid.tcPlanDay);
          }

          planDetail.forEach(function (detailItem, detailIndex) {
            var tableDeviceRead = `<tr>
                              <td>${detailItem.fia01 || ''}</td>
                              <td>${detailItem.fia02 || ''}</td>
                              <td>${detailItem.fic02 || ''}</td>
                              <td>${detailItem.pmc03 || ''}</td>
                              <td>${detailItem.tcSeriesName || ''}</td>
                              <td>${detailItem.fii02 || ''}</td>
                              <td colspan="6" class="subTd">
                                  <table class="subTable">
                                  </table>
                              </td>
                          </tr>`;
            var tableDeviceEdit = `<tr>
                              <td>
                                <input type="radio" name="project" lay-filter="checkArr" lay-skin="primary" data-id="${detailItem}"> </td>
                              <td>${detailItem.fia01 || ''}</td>
                              <td>${detailItem.fia02 || ''}</td>
                              <td>${detailItem.fic02 || ''}</td>
                              <td>${detailItem.pmc03 || ''}</td>
                              <td>${detailItem.tcSeriesName || ''}</td>
                              <td>${detailItem.fii02 || ''}</td>
                              <td colspan="6" class="subTd">
                                  <table class="subTable">
                                  </table>
                              </td>
                          </tr>`;
            $('#baseTable').find('> tbody').append(tableDeviceEdit)
            $('#readOnlyBaseTable').find('> tbody').append(tableDeviceRead);

            // 组装数据
            status.planDetails.push({
              tcDetailDevid: detailItem.tcDetailDevId,
              tcDetailId: detailItem.tcDetailId,
              planProjects: []
            })
            detailItem.isProject.forEach(function (projectItem, projectIndex) {
              var tableProjectRead = `<tr class="subTr">
                                    <td>${projectItem.tcInspName || ''}</td>
                                    <td>${projectItem.tcInspDsc || ''}</td>
                                    <td>${projectItem.tcInspUnit || ''}</td>
                                    <td>${projectItem.tcInspMax || ''}</td>
                                    <td>${projectItem.tcInspMin || ''}</td>
                                  </tr>`;
              var tableProjectEdit = `<tr class="subTr editTr">
                                    <td>${projectItem.tcInspName || ''}</td>
                                    <td>${projectItem.tcInspDsc || ''}</td>
                                    <td>${projectItem.tcInspUnit || ''}</td>
                                    <td>${projectItem.tcInspMax || ''}</td>
                                    <td>${projectItem.tcInspMin || ''}</td>
                                    <td>
                                       <span class="deleteProject delect icon mydel"></span>
                                    </td>
                                  </tr>`;

              $('#readOnlyBaseTable > tbody > tr').eq(detailIndex).find('.subTd .subTable').append(tableProjectRead)
              $('#baseTable > tbody > tr').eq(detailIndex).find('.subTd .subTable').append(tableProjectEdit)
              status.planDetails[detailIndex].planProjects.push({
                tcProjProjid: projectItem.tcInspId
              })
            })
          })
        }
      })
      // 启用停用
      $('.onOff-btn').click(function () {
        var planIds = [
          {
            tcPlanId: utill.getQueryVariable('planId'),
            tcPlanStatus: utill.getQueryVariable('tcPlanStatus')
          }
        ];
        // 启用0停用1
        var ajaxOpts = {
          url: api.host + api.xjjh.updateStatus,
          type: 'POST',
          contentType: 'application/json',
          data: JSON.stringify(planIds)
        }
        utill.loading.show();
        view.req(ajaxOpts).done(function (res) {
          var success = res.success;
          var data = res.data;

          utill.loading.hide();
          layer.msg(res.message)
          setTimeout(function () {
            $('.cancel-btn').click();
            table.reload('table-list')
          }, 1500)
        })
      })
    }
    init();
    var edit = function () {
      utill.fuzzmatch('#gen02');
      var nowTime = new Date();
      // 计划开始时间
      laydate.render({
        elem: "#startTime",
        type: "datetime",
        done: function (value, date, endDate) {
          var startDate = new Date($('#startTime').val()).getTime();
          var endTime = new Date(value).getTime();
          if (endDate < startDate) {
            layer.msg("计划结束时间不能小于开始时间");
            $("#startTime").val("");
          }
        }
      });
      // 计划结束时间
      laydate.render({
        elem: "#endTime",
        type: "datetime",
        done: function (value, date, endDate) {
          var startDate = new Date($('#startTime').val()).getTime();
          var endTime = new Date(value).getTime();
          if (endTime < startDate) {
            layer.msg("巡检结束时间不能小于巡检开始时间");
          }
        }
      });
      laydate.render({
        elem: '#tcPlanTime'
        , type: 'time'
        , format: 'HH:mm'
      });
      laydate.render({
        elem: '#tcPlanDuration'
        , type: 'time'
        , format: 'H.m'
        , max: '12:59:00'
        , btns: ['clear', 'confirm']
      });


      var verifys = {
        checkPlanDay: function (value, item) {
          var field = $(item).val();
          switch (status.tcPlanFrequency) {
            case "W":
              if (field.length == 0 || +field > 7) {
                return '<strong style="color: red">计划频率</strong>每周为必填项，且不能超过7';
              }
              break;
            case "M":
              if (field.length == 0 || +field > 28) {
                return '<strong style="color: red">计划频率</strong>每月为必填项，且不能超过28';
              }
              break;
            case "D":
              if (field.length > 0) {
                $("#tcPlanDay").val("");
                return '<strong style="color: red">计划频率</strong>每日无需填写';
              }
              break;
            case "H":
              if (field.length > 0) {
                $("#tcPlanDay").val("");
                return '<strong style="color: red">计划频率</strong>每小时无需填写';
              }
              break;
          }
        },
        toPlanDuration: function (value) {
          if (1 > +value > 24) {
            return '<strong style="color: red">执行时长</strong>必须是1至24之间';
          }
        }

      }
      //自定义验证规则
      form.verify(verifys);
      form.on('select(tcPlanFrequency)', function (data) {
        status.tcPlanFrequency = data.value;
      })
      form.on('radio(checkArr)', function (data) {
        status.deviceIndexArr = [];
        status.deviceIndexArr.push($(data.elem).parents('tr').index());
      })
      var alertEvent = {
        addDevice: function (layero, index) {
          form.render();
          table.render($.extend({}, utill.tableOpts(), {
            elem: '#table-device-alert',
            id: "#table-device-alert",
            height: 300,
            toolbar: '',
            url: api.host + api.xjjh.selectByFia01,
            where: {
              fia01: "",
              fia02: "",
              fia09: "",
              keyWord: "",
            },
            cols: [[
              { fixed: 'left', type: 'checkbox' },
              { field: 'fia01', title: '设备编号' },
              { field: 'fia02', title: '设备名称' },
              { field: 'fic02', title: '设备类型' },
              { field: 'pmc081', title: '供应商' },
              { field: 'tcSeriesName', title: '设备系列' },
              { field: 'fii02', title: '设备型号' }
            ]],


          }));
          form.on('submit(queryTableDeviceHeader)', function (data) {
            var allData = data.field;
            table.reload('#table-device-alert', {
              where: allData,
            });
            return false;
          })
          form.on('submit(queryTableDevice)', function (data) {
            var allData = data.field;
            table.reload('#table-device-alert', {
              where: allData,
            });
            return false;
          })
          utill.keyup('.searchInput', '.search-blank-icon');

          $('body').off('click', '.footer').on('click', '.footer', function (e) {
            var $target = $(e.target);
            if ($target.hasClass('btn1')) {
              var checkedArr = table.checkStatus('#table-device-alert').data;
              // 选中去重
              if (status.planDetails.length > 0) {
                for (var i = 0; i < status.planDetails.length; i++) {
                  for (var j = 0; j < checkedArr.length; j++) {
                    if (checkedArr[j].tcDevId == status.planDetails[i].tcDetailDevid) {
                      checkedArr.splice(j, 1)
                      j = j - 1;
                    }
                  }
                }
              }
              checkedArr.forEach(function (item, index) {
                var TPL = `<tr>
                  <td>
                    <input type="radio" name="project" lay-filter="checkArr" lay-skin="primary">
                  </td>
                  <td>${item.fia01 || ''}</td>
                  <td>${item.fia02 || ''}</td>
                  <td>${item.fic02 || ''}</td>
                  <td>${item.pmc081 || ''}</td>
                  <td>${item.tcSeriesName || ''}</td>
                  <td>${item.fii02 || ''}</td>
                  <td colspan="6">
                    <table class="subTable">
                    </table>
                  </td>
                </tr>`;
                $('#baseTable').find('> tbody').append(TPL);
                status.planDetails.push({
                  planProjects: [],
                  tcDetailDevid: item.tcDevId
                })
              })
              form.render();

            }
            layer.closeAll()
          });
        },
        addProject: function (layero, index) {
          form.render();
          table.render($.extend({}, utill.tableOpts(), {
            elem: '#table-project-alert',
            id: "#table-project-alert",
            height: 300,
            toolbar: '',
            cols: [[
              { fixed: 'left', type: 'checkbox' },
              { field: 'tcInspName', title: '项目名称' },
              { field: 'tcInspDsc', title: '项目说明' },
              { field: 'tcInspUnit', title: '单位' },
              { field: 'tcInspMax', title: '最高标准值' },
              { field: 'tcInspMin', title: '最低标准值' },
            ]],
            url: api.host + api.xjjh.selectProjectList,
            where: {
              tcInspName: "",
              tcInspUnit: "",
              keyWord: "",
              status: 0
            }
          }));
          form.on('submit(queryTableProjectHeader)', function (data) {
            var allData = data.field;
            allData['status'] = 0;
            table.reload('#table-project-alert', {
              where: allData,
            });
            return false;
          })
          form.on('submit(queryTableProject)', function (data) {
            var allData = data.field;
            allData['status'] = 0;
            table.reload('#table-project-alert', {
              where: allData,
            });
            return false;
          })
          utill.keyup('.searchInput', '.search-blank-icon');
          $('body').off('click', '.footer').on('click', '.footer', function (e) {
            var $target = $(e.target);
            if ($target.hasClass('btn1')) {
              var checkedArr = table.checkStatus('#table-project-alert').data;
              // 选中去重
              if (status.planDetails.length > 0) {
                var planProjects = status.planDetails[status.deviceIndexArr[0]].planProjects;
                for (var i = 0; i < planProjects.length; i++) {
                  for (var j = 0; j < checkedArr.length; j++) {
                    if (checkedArr[j].tcInspId == planProjects[i].tcProjProjid) {
                      checkedArr.splice(j, 1)
                      j = j - 1;
                    }
                  }
                }
              }
              
              checkedArr.forEach(function (item, index) {
                var TPL = `<tr class="subTr">
                                    <td>${item.tcInspName}</td>
                                    <td>${item.tcInspDsc}</td>
                                    <td">${item.tcInspUnit}</td>
                                    <td>${item.tcInspMax}</td>
                                    <td>${item.tcInspMin}</td>
                                    <td>
                                      <span class="deleteProject delect icon mydel"></span>
                                    </td>
                                  </tr>`;
                $('#baseTable').find('> tbody > tr').eq(status.deviceIndexArr[0]).find('> td:last-child').find('table').append(TPL);
                status.planDetails[status.deviceIndexArr[0]].planProjects.push({
                  tcProjProjid: item.tcInspId
                })
              })
              form.render();
              layer.closeAll()
            }
            layer.closeAll()
          });

        },
      }
      $('body').off('click', '.deleteProject').on('click', '.deleteProject', function (e) {
        var $target = $(e.target);
        var subIndex = $target.parents('.subTr').index();
        var parentId = $target.parents('.subTable').parents('tr').index();
        $target.parents('.subTr').remove();
        status.planDetails[parentId].planProjects.splice(subIndex, 1);
      })
      $('#deleteBaseInfo').click(function () {
        status.deviceIndexArr.forEach(function (itemIndex) {
          status.planDetails.splice(itemIndex, 1);
          status.deviceIndexArr.pop()
          $("#baseTable > tbody > tr").eq(itemIndex).remove();
        });
      })

      $('.btn-box').on('click', '.btn-one', function (e) {
        layer.open({
          type: 1,
          title: false,
          area: ['662px', '536px'],
          fixed: true,
          shadeClose: true,
          closeBtn: 0,
          content: $('#addDeviceTpl').html(),
          success: alertEvent.addDevice
        });
      })
      // //手动关联复选框
      form.on('checkbox(device)', function(data){
            if(data.elem.checked){
              $("[name='device-all']").next('.layui-unselect').addClass("layui-form-checked");
              $("[name='device-all']").attr("checked",true);
            }else{
              $("[name='device-all']").next('.layui-unselect').removeClass("layui-form-checked");
            $("[name='device']").attr("checked",false);
            }
      })
      
      form.on('checkbox(device-all)', function(data){
          if(data.elem.checked == true){
            $("[name='device']").next('.layui-unselect').addClass("layui-form-checked");
            $("[name='device']").attr("checked",true);
            $("[name='device-all']").attr("checked",true);
          }else{
            $("[name='device']").next('.layui-unselect').removeClass("layui-form-checked");
            $("[name='device']").attr("checked",false);
          }
      });
 
      $('.btn-box').on('click', '.btn-three', function (e) {
        let planProjectIds = [];
        let device_all =  $("[name='device-all']").attr("checked");
        $('input[name="device"]:checked').each(function () {//遍历每一个名字为nodes的复选框，其中选中的执行函数    
          if($(this).data('id') == false){
            return 
          }else{
            planProjectIds.push($(this).data('id')); 
          }
          if(planProjectIds){
          layer.confirm('确定删除选择的设备吗?', function (index) {
            let data = {
              planId: utill.getQueryVariable('planId'),
              planProjectIds:planProjectIds
            };
            utill.submit('/plan/deleteDetailAndProjdect.json',data,'readOnlyBaseTable','POST',{
              done:function(res){
                if(res.code == 0){
                  $("[data-id='false']").parents('tr').remove()
                  planProjectIds.forEach((item)=>{
                    $(`[data-id='${item}']`).parents('tr').remove()
                  })
                }
              }
            });
          })
        }else if($("[data-id='false']")){
          layer.confirm('确定删除选择的设备吗?', function (index) {
            $("[data-id='false']").parents('tr').remove()
            layer.open({
                content:'删除成功'
              });
            table.render()
          })
        }else{
          layer.open({
            content:'请选择要删除的设备'
          });
        }
        });
      })
      $('.btn-box').on('click', '.btn-two', function (e) {
        if (status.deviceIndexArr.length) {
          layer.open({
            type: 1,
            title: false,
            area: ['662px', '536px'],
            fixed: true,
            shadeClose: true,
            closeBtn: 0,
            content: $('#addProjectTpl').html(),
            success: alertEvent.addProject
          });
        } else {
          layer.msg('请选择一项数据进行操作！');
        }
      })

      // 提交
      form.on('submit(save)', function (data) {
        var baseData = data.field;
        if (!status.planDetails.length) {
          layer.msg('请添加巡检设备基本信息')
          return false;
        }
          var opts = {
            planDetails: status.planDetails
          }
          opts.tcPlanStatus1 = 0;
          opts = $.extend({}, opts, baseData);
          opts['tcPlanGen01'] = $('#gen02').data('id');
          utill.loading.show();
          delete opts.tcPlanCode
          view.req({
            url: api.host + api.xjjh.addDetailAndProjdect,
            type: 'POST',
            data: JSON.stringify(opts),
            contentType: 'application/json',
          }).done(function (res) {
            utill.loading.hide();
            if (res.code == "0") {
              setTimeout(function () {
                $('.cancel-btn').click();
              }, 1000);
            }
            layer.msg(res.message || '')
          })
          return false;
      })

      // 关闭
      $('.cancel-btn').attr('lay-href', 'patrol/balance');
      utill.dropdownEvent();
    }
    edit();
    tab($('#frequency').val());
    function tab(data){
      var val;
      if($("#tcPlanDay").val() != undefined){
         val = $("#tcPlanDay").val();
      }else{
         val = '';
      }
      if(data == 'H' || data == 'D'){
          $("[name='tcPlanDay']").attr('disabled','disabled');
          $(".freq").empty()
        }else if(data == 'W'){
          var tcPlanDayArr = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'];
          var str = `<select name="tcPlanDay" lay-filter="tcPlanDay" lay-verify="required" required id="frequency">`;
          tcPlanDayArr.forEach(function(elem,i){
            if(val == i+1){
              str +=  `<option value='${i+1}' selected class="layui-this">${elem}</option>`
            }else if(val == ""){
              str +=  `<option value='${i+1}'>${elem}</option>`
            }else{
              str +=  `<option value='${i+1}'>${elem}</option>`
            }
           
          })
          str += `</select>`;
          $(".freq").html(str);
          form.render('select');
        }else if(data == 'M'){
          let frequency = $('.layui-this:selected').val()
          let el_data;
          if(val != "" && val != undefined){
            el_data = val
          }else if(frequency != undefined){
            el_data = frequency;
          }else{
            el_data = '';
          }
          $(".freq").empty()
          var str =  `<input name="tcPlanDay" id="tcPlanDay" autocomplete="off" class="layui-input" required
              lay-verify="required" lay-filter="tcPlanDay" placeholder="请输入1至28纯数字" title="请输入1至28有效数字"  value="${el_data}"/>`;
          $(".freq").html(str);

        }
    }
    $('.showCanEdit').click(function () {
      $('#onlyReadContent').addClass('hide');
      $('#canEditContent').removeClass('hide');
       tab($('#frequency').val());
      form.on('select(tcPlanFrequency)', function(data){
        tab(data.value);
      })
      form.render();
    })
    $('.cancelBtn').click(function () {
      $('#canEditContent').addClass('hide');
      $('#onlyReadContent').removeClass('hide');
      form.render();
    })
  });


  $('[data-jump="patrol/balance"]').addClass('layui-this');
}();
</script>
<style scoped>
.btn-three{
    flex-flow: row nowrap;
    width: auto;
    height: 20px;
    line-height: 20px;
    font-size: 9px;
    color: #fff;
    padding: 0 5px;
    border: 0;
    background-color:#FF4C4C;
  }
.hide {
  display: none;
}

.cancelBtn {
  color: #666;
  font-size: 14px;
}

.leon-style .layui-input-block {
  display: flex;
  align-items: center;
  justify-content: start;
}

.leon-style .layui-textarea-block {
  min-height: 35px;
}

.leon-style .layui-textarea {
  line-height: 1;
  min-height: 40px;
  resize: vertical;
}

.leon-style .layui-radio-box {
  height: 14px;
}

.leon-style .layui-radio-box .layui-form-radio {
  margin: 0;
  margin-right: 10px;
}
.deleteProject{
  width: 20px;
  display: flex;
  margin: 0 auto;
}
.leon-style .box {
  overflow: inherit;
}

.leon-style .layui-form-radio>i {
  font-size: 15px;
}

.leon-style .layui-form-radio>div {
  font-size: 12px;
}

.leon-style .layui-table-tool {
  display: none;
}

.leon-style .layui-table[lay-size=sm] th,
.leon-style .layui-table-cell {
  padding: 0;
}
.deleteProject .layui-form-checkbox[lay-skin=primary]{
  display: inline-block;
}
.myedit{
  display:flex;
  justify-content: center;
  align-items: center
}
.myedit .layui-unselect{
  margin-left: 20px;
}
#baseTable td table {
  width: 100%;
}

/*不显示秒*/
#layui-laydate4 .layui-laydate-content>.layui-laydate-list {
  padding-bottom: 0px;
  overflow: hidden;
}

#layui-laydate4 .layui-laydate-content>.layui-laydate-list>li {
  width: 50%
}

#layui-laydate4 .merge-box .scrollbox .merge-list {
  padding-bottom: 5px;
}

.layui-table[lay-size=sm] .subTd {
  padding: 0;
}

.subTable .subTr td {
  width: 10%;
  white-space: pre-wrap;
}

.subTable .editTr.editTr td {
  width: 8%;
  white-space: pre-wrap;
}
.layui-form-radio{
  margin: 0px;
}
#tcPlanStatus{
  justify-content: center;
}
#tcPlanStatus .layui-unselect{
  margin-right: 10px;
}
</style>